package com.ruoyi.project.monitor.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.constant.ApiImplicitParamType;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.R;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.monitor.domain.SysUserOnline;
import com.ruoyi.project.system.service.ISysUserOnlineService;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 在线用户监控
 * 
 * @author ruoyi
 */
@Api(tags = "在线用户")
@RestController
@RequestMapping("/monitor/online")
public class SysUserOnlineController extends BaseController
{
    @Autowired
    private ISysUserOnlineService userOnlineService;

    @Autowired
    private RedisCache redisCache;

    @ApiOperation("在线用户列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "ipaddr", value = "IP地址", dataType = "String", dataTypeClass = String.class),
        @ApiImplicitParam(name = "userName", value = "用户名称", dataType = "String", dataTypeClass = String.class),
    })
    @SaCheckPermission("monitor:online:list")
    @GetMapping("/list")
    public TableDataInfo<SysUserOnline> list(String ipaddr, String userName)
    {
    	List<String> tokens = StpUtil.searchTokenValue("", 0, -1, false);
        List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
        for (String token : tokens)
        {
        	String []tokenSplit = token.split(":");
        	String key = CacheConstants.getTokenKey(tokenSplit[tokenSplit.length-1]);
            LoginUser user = redisCache.getCacheObject(key);
            if(user == null) {
            	continue;
            }
            user.setTokenTimeout(StpUtil.getTokenTimeout(token));
            user.setTokenActiveTimeout(StpUtil.getStpLogic().getTokenActiveTimeoutByToken(token));
            if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName))
            {
				//if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(username, user.getUsername())) {
                userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
            }
            else if (StringUtils.isNotEmpty(ipaddr))
            {
				//if (StringUtils.equals(ipaddr, user.getIpaddr())) {
                userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
            }
            else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser()))
            {
                userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
            }
            else
            {
                userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
            }
        }
//        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        return getDataTable(userOnlineList);
    }

    /**
     * 强退用户
     */
    @ApiOperation("强退用户")
    @ApiImplicitParam(name = "tokenId", value = "tokenId", required = true, dataType = "String", paramType = ApiImplicitParamType.PATH, dataTypeClass = String.class)
    @SaCheckPermission("monitor:online:forceLogout")
    @Log(title = "在线用户", businessType = BusinessType.FORCE)
    @DeleteMapping("/{tokenId}")
    public R<String> forceLogout(@PathVariable String tokenId)
    {
    	StpUtil.logoutByTokenValue(tokenId);
        redisCache.deleteObject(CacheConstants.getTokenKey(tokenId));
        return success();
    }
}
